package com.example.dao;

import com.example.domain.User;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.List;
import java.util.Optional;
import java.util.Scanner;

/**
 * 用户管理系统
 * 提供手动CRUD操作功能
 */
public class Test {

    public static void main(String[] args) {
        try {
            // 获取数据库连接
            String url = "jdbc:mysql://localhost:3306/eshop?serverTimezone=Asia/Shanghai&useSSL=false&allowPublicKeyRetrieval=true";
            String user = "root";
            String pwd = "1625344721Qq@";
            Connection connection = DriverManager.getConnection(url, user, pwd);
            
            UserDao userDao = new UserDao(connection);

            try {
                Scanner scanner = new Scanner(System.in);
                
                while (true) {
                    System.out.println("\n=== 用户管理系统 ===");
                    System.out.println("1. 创建用户");
                    System.out.println("2. 查看所有用户");
                    System.out.println("3. 根据ID查找用户");
                    System.out.println("4. 更新用户");
                    System.out.println("5. 删除用户");
                    System.out.println("0. 退出");
                    System.out.print("请选择操作: ");
                    
                    int choice = scanner.nextInt();
                    scanner.nextLine(); // 消费换行符
                    
                    switch (choice) {
                        case 1:
                            createManualUser(userDao, scanner);
                            break;
                        case 2:
                            showAllUsers(userDao);
                            break;
                        case 3:
                            findUserById(userDao, scanner);
                            break;
                        case 4:
                            updateUser(userDao, scanner);
                            break;
                        case 5:
                            deleteUser(userDao, scanner);
                            break;
                        case 0:
                            System.out.println("退出系统");
                            return;
                        default:
                            System.out.println("无效选项，请重新选择");
                    }
                }
                
            } catch (Exception e) {
                System.err.println("操作过程中发生异常：" + e.getMessage());
                e.printStackTrace();
            } finally {
                connection.close();
            }
        } catch (Exception e) {
            System.err.println("数据库连接失败：" + e.getMessage());
            e.printStackTrace();
        }
    }

    private static void createManualUser(UserDao userDao, Scanner scanner) throws Exception {
        User newUser = new User();
        
        System.out.print("请输入用户名: ");
        newUser.setUsername(scanner.nextLine());
        
        System.out.print("请输入真实姓名: ");
        newUser.setRealname(scanner.nextLine());
        
        System.out.print("请输入邮箱: ");
        newUser.setEmail(scanner.nextLine());
        
        System.out.print("请输入密码: ");
        newUser.setPassword(scanner.nextLine());
        
        System.out.print("请输入电话: ");
        newUser.setPhone(scanner.nextLine());
        
        userDao.createUser(newUser);
        System.out.println("用户创建成功！");
    }

    private static void showAllUsers(UserDao userDao) throws Exception {
        List<User> users = userDao.getAllUsers();
        System.out.println("用户总数: " + users.size());
        if (users.isEmpty()) {
            System.out.println("暂无用户数据");
        } else {
            System.out.println("--- 用户列表 ---");
            for (User user : users) {
                System.out.println(user.toString());
            }
        }
    }

    private static void findUserById(UserDao userDao, Scanner scanner) throws Exception {
        System.out.print("请输入要查找的用户ID: ");
        int userId = scanner.nextInt();
        scanner.nextLine(); // 消费换行符
        
        Optional<User> userOptional = userDao.getUserById(userId);
        if (userOptional.isPresent()) {
            System.out.println("找到用户: " + userOptional.get().toString());
        } else {
            System.out.println("未找到ID为 " + userId + " 的用户");
        }
    }

    private static void updateUser(UserDao userDao, Scanner scanner) throws Exception {
        System.out.print("请输入要更新的用户ID: ");
        int userId = scanner.nextInt();
        scanner.nextLine(); // 消费换行符
        
        Optional<User> userOptional = userDao.getUserById(userId);
        if (!userOptional.isPresent()) {
            System.out.println("未找到ID为 " + userId + " 的用户");
            return;
        }
        
        User user = userOptional.get();
        System.out.println("当前用户信息: " + user.toString());
        
        System.out.print("请输入新的用户名 (当前: " + user.getUsername() + "): ");
        String username = scanner.nextLine();
        if (!username.isEmpty()) {
            user.setUsername(username);
        }
        
        System.out.print("请输入新的真实姓名 (当前: " + user.getRealname() + "): ");
        String realname = scanner.nextLine();
        if (!realname.isEmpty()) {
            user.setRealname(realname);
        }
        
        System.out.print("请输入新的邮箱 (当前: " + user.getEmail() + "): ");
        String email = scanner.nextLine();
        if (!email.isEmpty()) {
            user.setEmail(email);
        }
        
        System.out.print("请输入新的密码 (当前: " + user.getPassword() + "): ");
        String password = scanner.nextLine();
        if (!password.isEmpty()) {
            user.setPassword(password);
        }
        
        System.out.print("请输入新的电话 (当前: " + user.getPhone() + "): ");
        String phone = scanner.nextLine();
        if (!phone.isEmpty()) {
            user.setPhone(phone);
        }
        
        userDao.updateUser(user);
        System.out.println("用户信息更新成功！");
    }

    private static void deleteUser(UserDao userDao, Scanner scanner) throws Exception {
        System.out.print("请输入要删除的用户ID: ");
        int userId = scanner.nextInt();
        scanner.nextLine(); // 消费换行符
        
        Optional<User> userOptional = userDao.getUserById(userId);
        if (!userOptional.isPresent()) {
            System.out.println("未找到ID为 " + userId + " 的用户");
            return;
        }
        
        System.out.println("找到用户: " + userOptional.get().toString());
        System.out.print("确认删除该用户吗？(y/n): ");
        String confirm = scanner.nextLine();
        
        if ("y".equalsIgnoreCase(confirm)) {
            userDao.deleteUser(userId);
            System.out.println("用户删除成功！");
        } else {
            System.out.println("取消删除操作");
        }
    }
}